# coding:utf-8
from PyQt5.QtCore import QDateTime, QTimer, Qt, QEvent
from PyQt5.QtWidgets import QWidget
from qfluentwidgets import FluentIcon

from view.Ui_StopWatchInterface import Ui_StopWatchInterface


class StopWatchInterface(Ui_StopWatchInterface, QWidget):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_stopwatch)
        self.start_time = 0
        self.lastTime = 0
        self.current_time = 0
        self.current_status = False

        self.startButton.setIcon(FluentIcon.PLAY)
        self.startButton.clicked.connect(self.start)
        self.flagButton.setIcon(FluentIcon.ROTATE)
        self.flagButton.clicked.connect(self.reset)
        self.restartButton.setIcon(FluentIcon.STOP_WATCH)
    def update_stopwatch(self):
        current_time = QDateTime.currentMSecsSinceEpoch() - self.start_time
        self.current_time = current_time + self.lastTime
        time_elapsed = self.ms_to_time(current_time + self.lastTime)
        self.timeLabel.setText(time_elapsed)

    def start(self):
        self.startButton.setChecked(True)
        if self.current_status:
          self.current_status = False
          self.startButton.setIcon(FluentIcon.PLAY)
          self.flagButton.setEnabled(True)
          self.lastTime = self.current_time
          self.stop()
        else:
          self.current_status = True
          self.startButton.setIcon(FluentIcon.PAUSE)
          self.flagButton.setEnabled(False)
          self.start_time = QDateTime.currentMSecsSinceEpoch()
          self.timer.start(1)  # 1 ms interval

    def stop(self):
        self.timer.stop()

    def reset(self):
        self.flagButton.setChecked(False)
        self.timeLabel.setText("00:00.000")
        self.start_time = 0
        self.lastTime = 0
        self.current_time = 0

    def ms_to_time(self, milliseconds):
        seconds, milliseconds = milliseconds // 1000, milliseconds % 1000
        minutes = seconds // 60
        seconds = seconds % 60
        return '{:02d}:{:02d}.{:03d}'.format(minutes, seconds, milliseconds)
